package com.zb.kc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Sets;
import com.sun.org.apache.xml.internal.dtm.ref.sax2dtm.SAX2DTM2;
import com.zb.kc.entity.District;
import com.zb.kc.dao.DistrictDao;
import com.zb.kc.service.IDistrictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wanggen
 * @since 2020-04-17
 */
@Service
public class DistrictServiceImpl extends ServiceImpl<DistrictDao, District> implements IDistrictService {

    @Override
    public District getAllDistrict() {
        // 根节点中国
        District china = baseMapper.selectById(1);
        // 所有的一级节点
        List<District> levelOne = baseMapper.selectList(new QueryWrapper<District>().eq("parentId", 1));
        // 所有剩余节点
        List<District> others = baseMapper.selectList(new QueryWrapper<District>().ne("parentId", 1));
        Set<Integer> districtIds = Sets.newHashSetWithExpectedSize(others.size());
        levelOne.forEach(o -> {
            getChildren(o, others, districtIds);
        });
        china.setChildren(levelOne);
        return china;
    }

    private void getChildren(District o, List<District> others, Set<Integer> districtIds) {
        List<District> children = new ArrayList<>();
        others.stream()
                .filter(district -> !districtIds.contains(district.getId()))
                .filter(district -> o.getId().equals(district.getParentId()))
                .forEach(child -> {
                    districtIds.add(child.getId());
                    getChildren(child, others, districtIds);
                    children.add(child);
                });
        o.setChildren(children);
    }
}
